import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { userApi } from '@/services/api';
import { useToast } from '@/hooks/use-toast';

interface User {
  id: number;
  userName?: string;
  userAccount: string;
  userAvatar?: string;
  userProfile?: string;
  userRole: string;
  createTime: string;
  updateTime: string;
  token?: string;
}

interface AuthContextType {
  user: User | null;
  loading: boolean;
  login: (userData: User) => void;
  logout: () => void;
  updateUser: (userData: Partial<User>) => void;
  isAuthenticated: boolean;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const { toast } = useToast();

  // 检查用户登录状态
  useEffect(() => {
    checkAuthStatus();
  }, []);

  const checkAuthStatus = async () => {
    const token = localStorage.getItem('token');
    if (!token) {
      setLoading(false);
      return;
    }

    try {
      const response = await userApi.getLoginUser();
      if (response.code === 0) {
        setUser(response.data);
      } else {
        // token无效，清除本地存储
        localStorage.removeItem('token');
      }
    } catch (error) {
      console.error('检查登录状态失败:', error);
      localStorage.removeItem('token');
    } finally {
      setLoading(false);
    }
  };

  const login = (userData: User) => {
    setUser(userData);
    if (userData.token) {
      localStorage.setItem('token', userData.token);
    }
  };

  const logout = async () => {
    try {
      await userApi.logout();
    } catch (error) {
      console.error('注销失败:', error);
    } finally {
      setUser(null);
      localStorage.removeItem('token');
      toast({
        title: "已退出登录",
        description: "感谢您的使用！",
      });
    }
  };

  const updateUser = (userData: Partial<User>) => {
    if (user) {
      setUser({ ...user, ...userData });
    }
  };

  const value: AuthContextType = {
    user,
    loading,
    login,
    logout,
    updateUser,
    isAuthenticated: !!user,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}